package com.fz.song.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig {

    /**
     * 把数据源注册进来
     */
    @Autowired
    DataSource dataSource;

    /**
     * 注册一个密码加密工具
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 注册一个UserDetailsService,使用内存存储用户以及角色
     *WebSecurityConfig的configure(AuthenticationManagerBuilder)这个方法这可以注册
     * @return
     */


    @Bean
    public UserDetailsService userDetailsService() {
        JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
        //设置数据源
        manager.setDataSource(dataSource);
        if (!manager.userExists("sysdba")) {
            manager.createUser(User.withUsername("sysdba").password("$2a$10$9V22q06joNdW6w9kWVjhveyLIiVeMcit0TfHy0ZrsI6COI8sjwLLW").roles("ADMIN", "USER").build());
        }
        if (!manager.userExists("admin")) {
            manager.createUser(User.withUsername("admin").password("$2a$10$lIobeU6HkS2ZPTGFv5wNDuK2DmjtNRyRCe8D505UhWFO4./06rGWq").roles("ADMIN").build());
        }
        if (!manager.userExists("user")) {
            manager.createUser(User.withUsername("user").password("$2a$10$1PUcJzgivcCIBGGU2MPk/.NaBtaxs9eyEJFCF5dkU.1Q9Mxa9GqUW").roles("USER").build());
        }
        return manager;
    }
}
